use serde::{Deserialize, Serialize};
use serde_json::{json};
use sqlx::postgres::{PgPool,};
use axum::{
    extract::{Extension, Path,},
    Json,
};
use crate::middleware::{
    error::Error,
    response::{MyResponseStruct,MyResponse}
    // db::{ResData}
};

#[derive(Serialize,Deserialize,Clone)]
pub struct Good {
    goodname: String,
    des: String,
    price:i32,
}

//getall
pub async fn get_all_goods(Extension(pool):Extension<PgPool>)->Result<Json<MyResponseStruct>,Error>{
    let res:Vec<Good> = sqlx::query!("select * from goods").fetch_all(&pool).await?
        .into_iter().map(|x|Good { goodname: x.goodname, des: x.des, price: x.price }).collect();

    Ok(MyResponse::Success(json!(res)).into())
}
//getBuyId
pub async fn get_by_id(Path(id):Path<i32> ,Extension(pool):Extension<PgPool>)->Result<Json<Good>,Error>{
    let res = sqlx::query!("select * from goods where id=$1",id).fetch_one(& pool).await?;
    let good= Good{
        goodname:res.goodname,
        des:res.des,
        price:res.price
    };
    Ok(good.into())
}
//creat
pub async fn add_good(Json(params):Json<Good>,Extension(pool):Extension<PgPool>)->Result<Json<i32>,Error>{
    let res = sqlx::query!("insert  into  goods(goodname,des,price) values ($1,$2,$3) returning id",params.goodname,params.des,params.price)
    .fetch_one(& pool).await?;
    Ok(res.id.into())
}
//updata
pub async fn update_good(Path(id): Path<i32> ,Json(params):Json<Good>,Extension(pool):Extension<PgPool>)->Result<Json<u64>,Error>{
    let res = sqlx::query!("update  goods set goodname=$1, des=$2, price=$3where id=$4",params.goodname,params.des,params.price,id)
    .execute(&pool).await?.rows_affected();
    Ok(res.into())
}
//delete
pub async fn delete_good(Path(id): Path<i32>,Extension(pool):Extension<PgPool>)->Result<Json<u64>,Error>{
    let res =sqlx::query!("delete from goods where id=$1",id).execute(&pool).await?.rows_affected();
    Ok(res.into())
}



